package com.skp.shaphan.ui.results;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;

import com.skp.job.ProjectJobException;

/**
 * A Table Column Model for the ResultsTable.
 * @author Stephen Phillips
 *
 */
public class ResultsColumnModel extends DefaultTableColumnModel {
	ResultSet results;
	
	public ResultsColumnModel() {
		results = null;
		this.addColumn(new TableColumn());
	}
	
	public void setResults(ResultSet results) {
		while(this.getColumnCount() > 0) {
			this.removeColumn(this.getColumn(0));
		}
		if(results == null) {
			return;
		}
		TableColumn col;
		try {
			ResultSetMetaData meta = results.getMetaData();
			for(int x=1; x<=meta.getColumnCount(); x++) {
				col = new TableColumn();
				col.setHeaderValue(meta.getColumnLabel(x));
				col.setModelIndex(x-1);
				this.addColumn(col);
			}
		} catch (SQLException e) {
			(new ProjectJobException(e)).displayException();
			throw new Error("SQL Error: " + e.getLocalizedMessage(), e);
		}
	}

	@Override
	public TableColumn getColumn(int columnIndex) {
		if(tableColumns.size() == 0) {
			this.addColumn(new TableColumn());
		}
		return super.getColumn(columnIndex);
	}
	
}
